package com.example.demo.leetcode;

public class leetcode004 {

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int size1 = nums1.length;
        int size2 = nums2.length;
        int size = size1 + size2;

        int mid = size / 2; //  4 / 2 = 2 后一个元素的位置索引;  3 / 2 = 1 中间元素的位置索引
        double result = 0;

        int p1 = 0, p2 = 0; //两个指针

        if (size % 2 == 1) {// 奇数
            for (int i = 0; i < size; i++) {
                if (i == mid) {
                    if (p1 == size1) {
                        result = nums2[p2];
                    } else if (p2 == size2) {
                        result = nums1[p1];
                    } else if (nums1[p1] <= nums2[p2]) {
                        result = nums1[p1];
                    } else if (nums1[p1] > nums2[p2]) {
                        result = nums2[p2];
                    }
                    break;
                } else {
                    if (p1 == size1) {
                        p2++;
                    } else if (p2 == size2) {
                        p1++;
                    } else if (nums1[p1] <= nums2[p2]) {
                        p1++;
                    } else if (nums1[p1] > nums2[p2]) {
                        p2++;
                    }
                }
            }
        } else {
            int pre = 0; //记录前一个元素
            for (int i = 0; i < size; i++) {
                if (i == mid) {
                    if (p1 == size1) {
                        result = (nums2[p2] + pre) / 2.0;
                    } else if (p2 == size2) {
                        result = (nums1[p1] + pre) / 2.0;
                    } else if (nums1[p1] <= nums2[p2]) {
                        result = (nums1[p1] + pre) / 2.0;
                    } else if (nums1[p1] > nums2[p2]) {
                        result = (nums2[p2] + pre) / 2.0;
                    }
                    break;
                } else {
                    if (p1 == size1) {
                        pre = nums2[p2];
                        p2++;
                    } else if (p2 == size2) {
                        pre = nums1[p1];
                        p1++;
                    } else if (nums1[p1] <= nums2[p2]) {
                        pre = nums1[p1];
                        p1++;
                    } else if (nums1[p1] > nums2[p2]) {
                        pre = nums2[p2];
                        p2++;
                    }
                }
            }
        }

        return result;
    }
}
